<?php
/**
 * Created by PhpStorm.
 * User: longli
 * Date: 2021/07/20
 * Time: 15:20
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\ProductKeywordCategory;
use app\common\service\product\ProductService;
use think\facade\Cache;
use think\facade\Validate;

/**
 * 关键词分类
 * Class KcateController
 * @package app\admin\controller\wms
 */
class KcateController extends BaseController
{
    /**
     * 分类列表
     * @date 2021/07/20
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $list = ProductKeywordCategory::getAllByTree();
            $this->assign("list", $list);
            return $this->fetch('lists');
        }
        return $this->fetch("index");
    }

    /**
     * 更新分类信息
     * @date 2021/07/20
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'parent_id'  => 'require',
                'name' => 'require'
            ],[
                'parent_id.require' => '父类必选',
                'name.require' => '名称必填',
            ]);
            $data = $this->request->post();
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
            if(!isset($data['status'])) $data['status'] = ProductKeywordCategory::IS_NO;
        }
        else
        {
            $validate = Validate::make([
                'cate_id'  => 'require',
            ],[
                'cate_id.require' => '非法请求',
            ]);
            $data = $this->request->only(['cate_id', 'status'], 'get');
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
        }
        ProductService::getInstance()->addKeywordCategory($data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 添加分类
     * @date 2021/07/20
     * @author longli
     */
    public function add()
    {
        $cates = ProductKeywordCategory::order("parent_id")->select()->toArray();
        $cates = Tools::generateTree($cates, 'cate_id', 'parent_id');
        $cates = Tools::levelArray($cates);
        $this->assign("category", $cates);
        $cateId = $this->request->get("cate_id");
        if(!empty($cateId)) $this->assign("cate", ProductKeywordCategory::get($cateId));
        return $this->fetch("add");
    }

    /**
     * 删除分类
     * @date 2021/07/20
     * @author longli
     */
    public function delete()
    {
        $cateId = $this->request->request("ids");
        if(empty($cateId)) $this->error('参数错误');
        ProductKeywordCategory::destroy($cateId);
        $this->success('删除成功');
    }
}